﻿using EasyXaf.EntityDesigner.BusinessObjects.Entities;
using EasyXaf.EntityDesigner.BusinessObjects.Entities.EntityProperties;

namespace EasyXaf.EntityDesigner.Editors.DetailViewEditors.Models;

public class EntityTreeNode
{
    private List<EntityTreeNode> _children;

    public string Name { get; }

    public string Text { get; }

    public string CssClass { get; }

    public string ImageUrl { get; }

    public string PropertyPath
    {
        get
        {
            if (EntityProperty != null)
            {
                var parentPath = ParentNode?.PropertyPath;
                if (!string.IsNullOrWhiteSpace(parentPath))
                {
                    return $"{parentPath}.{EntityProperty.Name}";
                }
                return EntityProperty.Name;
            }
            return null;
        }
    }

    public bool HasChildren
    {
        get
        {
            if (EntityProperty == null)
            {
                return true;
            }

            if (EntityProperty.PropertyType == PropertyType.Entity)
            {
                if (EntityProperty.EntityType != null)
                {
                    return true;
                }
            }

            return false;
        }
    }

    public List<EntityTreeNode> Children => _children ??= GetChildren();

    public EntityProperty EntityProperty { get; }

    public EntityTreeNode ParentNode { get; }

    public Entity RootEntity { get; }

    public EntityTreeNode(Entity rootEntity, EntityTreeNode parentNode, EntityProperty entityProperty)
    {
        RootEntity = rootEntity;
        ParentNode = parentNode;
        EntityProperty = entityProperty;

        if (EntityProperty != null)
        {
            Name = PropertyPath;
            Text = EntityProperty.DisplayName;
            CssClass = $"entity-tree-node entity-property-node p-path-{Name}";
            ImageUrl = $"IImageService/{EntityProperty.PropertyTypeImage}";
        }
        else
        {
            Text = RootEntity.DisplayName;
            CssClass = "entity-tree-node";
            ImageUrl = "IImageService/designer-form";
        }
    }

    private List<EntityTreeNode> GetChildren()
    {
        IEnumerable<EntityProperty> properties = [];

        if (EntityProperty == null)
        {
            properties = RootEntity.UseableProperties;
        }
        else if (EntityProperty.PropertyType == PropertyType.Entity && EntityProperty.EntityType != null)
        {
            properties = EntityProperty.EntityType.UseableProperties;
        }

        return properties
            .Where(p => p.IsBrowsable != BusinessObjects.DefaultBoolean.False)
            .Where(p => p.PropertyType != PropertyType.Unknown)
            .Select(p => new EntityTreeNode(RootEntity, this, p))
            .ToList();
    }
}
